package com.lixw.langchain.config;

import cn.hutool.core.util.IdUtil;
import dev.langchain4j.model.chat.ChatModel;
import dev.langchain4j.model.chat.listener.ChatModelErrorContext;
import dev.langchain4j.model.chat.listener.ChatModelListener;
import dev.langchain4j.model.chat.listener.ChatModelRequestContext;
import dev.langchain4j.model.chat.listener.ChatModelResponseContext;
import dev.langchain4j.model.openai.OpenAiChatModel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.time.Duration;
import java.util.List;

/**
 * @ClassName: LLMConfig
 * @Description:
 * @Author: xuweiLi
 * @Create: 2025/8/22 20:36
 **/
@Slf4j
@Configuration
public class LLMConfig {
    @Bean
    public ChatModel chatModelQwen(@Qualifier("myChatModelListener") ChatModelListener myChatModelListener) {
        return OpenAiChatModel.builder()
                .baseUrl("https://dashscope.aliyuncs.com/compatible-mode/v1")
                .apiKey(System.getenv("QWEN_API_KEY"))
                .modelName("qwen-plus")
                .logRequests(true)
                .logResponses(true)
                //.maxRetries(2)
                //.timeout(Duration.ofSeconds(1))
                .listeners(List.of(myChatModelListener))
                .build();
    }

    @Bean
    public ChatModelListener myChatModelListener(){
        return new ChatModelListener() {
            @Override
            public void onRequest(ChatModelRequestContext requestContext) {
                String uuidValue = IdUtil.simpleUUID();
                requestContext.attributes().put("traceId", uuidValue);
                log.info("onRequest(): {}, 业务id:{}", requestContext.chatRequest(),uuidValue);
            }

            @Override
            public void onResponse(ChatModelResponseContext responseContext) {
                Object traceId = responseContext.attributes().get("traceId");
                log.info("onResponse(): {}, 业务id:{}", responseContext.chatResponse(),traceId);
            }

            @Override
            public void onError(ChatModelErrorContext errorContext) {
                log.info("onError(): {}", errorContext.error().getMessage());
            }
        };
    }
}